package com.monitor.common;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName OkHttpUtil
 * @Package com.monitor.common
 * @Description OkHttpUtil
 * @Author zhixingbai
 * @Create 2018/10/1417:05
 */
public class OkHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    /**
     * post
     * @param url 请求的url
     * @return
     */
    public static String post(String url, String jsonString) throws Exception{
        logger.info("请求地址：{}，请求参数：{}",url,jsonString);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, jsonString);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            logger.info("返回状态：{}",status);
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("okhttp3 post error >> ex = {}",e.getMessage());
            throw  e;
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
}
